from user import  models
from rest_framework import serializers
import re
#验证邮箱
def checkemail(value):
  if not re.match(r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$', value):
    raise serializers.ValidationError("邮箱格式不正确")
  else:
    emaildata=models.UserModel.objects.filter(email=value)
    if emaildata:
      raise serializers.ValidationError("邮箱已存在")
#验证手机号
def checkphone(value):
  if not re.match(r'^1[3456789]\d{9}$', value):
    raise serializers.ValidationError("手机号格式不正确")
  phonedata = models.UserModel.objects.filter(phone=value)
  if phonedata:
    raise serializers.ValidationError("手机号已存在")
class SerUser(serializers.ModelSerializer):
  class Meta:
    model = models.UserModel
    fields = "__all__"
    extra_kwargs = {
      "email":{
        "error_messages":{
          "required":"邮箱不能为空",
          "unique":"邮箱已存在",
        },
        "validators":[checkemail]
      },
      "phone":{
        "error_messages":{
          "required":"手机号不能为空",
          "unique":"手机号已存在",
        },
        "validators":[checkphone]
      },
      "password":{
        "max_length":10,
        "min_length":6,
        "error_messages":{
          "required":"密码不能为空",
          "max_length":"密码长度不能超过10位",
          "min_length":"密码长度不能少于6位",
        }
      },
      "username":{
        "error_messages":{
          "required":"用户名不能为空",
          "unique":"用户名已存在"
        }
      }
    }

class CouponSer(serializers.ModelSerializer):
  class Meta:
    model = models.CouponModel
    fields = "__all__"
class UserCouponSer(serializers.ModelSerializer):
  coudetail=serializers.SerializerMethodField(read_only=True)
  def get_coudetail(self,obj):
    return{"condition":obj.coupon.condition,"name":obj.coupon.name,"price":obj.coupon.price,"start_time":obj.coupon.created_time,"end_time":obj.coupon.end_time}
  class Meta:
    model = models.UserCoupon
    fields = "__all__"
